package com.apts.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.apts.constant.Constant_PlanB_;
import com.apts.jfinalbase.BaseController;
import com.apts.jfinalbase.BaseJsonPojo;
import com.apts.pojo.ErrorPojo;
import com.apts.pojo.NomalPojo;
import com.apts.servise.Servise_PlanB_;
import com.apts.util.ImgCode;
import com.apts.util.JfinalFileUtil;
import com.apts.util.ResponseUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

/**
 * 全局备用
 * 
 * @author lwh api : /api/planb
 */
public class Controller_PlanB_ extends BaseController {
	public static Logger log4j = Logger.getLogger(Controller_PlanB_.class);

	/**
	 * 获取验证码
	 */
	public void getCode() {
		ImgCode img = ImgCode.create().init(80, 40, 4, 0);
		String codeStr = img.getCode();
		HttpSession session = this.getSession();
		if (session.getAttribute("code") != null) {
			session.removeAttribute("code");
		}
		session.setAttribute("code", codeStr);
		log4j.info("保存验证码到当前用户会话中：inSessionCode: " + session.getAttribute("code"));
		// 设置Response响应头信息
		HttpServletResponse res = ResponseUtil.init(this.getResponse()).setStreamContentType("image/jpeg")
				.getResponse();
		try {
			ImageIO.write(img.getBufferedImage(), "jpg", res.getOutputStream());
			res.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 使用Response渲染返回Null
		this.renderNull();
	}

	/**
	 * 用户登录
	 */
	public void doLogin() {
		HttpSession session = this.getSession();
		log4j.info("执行到这里：inSessionCode: " + session.getAttribute("code"));
		BaseJsonPojo msgJson;
		String inSessionCode = (String) session.getAttribute("code");
		log4j.info("执行到这里：inSessionCode: " + session.getAttribute("code") + "   " + inSessionCode);
		if (inSessionCode == null) {
			msgJson = new ErrorPojo();
			msgJson.setMsg("验证码错误");
			this.renderJson(msgJson);
			log4j.info("执行到这里: inSessionCode == null");
			return;
		}
		String userInputCode = this.getPara("code");
		String account = this.getPara("account");
		String password = this.getPara("password");
		// 判断验证码
		if (!inSessionCode.equals(userInputCode.toLowerCase())) {
			msgJson = new ErrorPojo();
			msgJson.setMsg("验证码错误！");
			log4j.info("执行到这里: 验证码错误！");
			session.removeAttribute("code");
			this.renderJson(msgJson);
			return;
		}
		// 密码验证
		Map<String, Object> obj = Servise_PlanB_.servise.findAccount(account, password);
		if (obj == null) {
			msgJson = new ErrorPojo();
			msgJson.setMsg("账号或密码错误！");
			log4j.info("执行到这里: 账号或密码错误！");
			session.removeAttribute("code");
			this.renderJson(msgJson);
			return;
		}
		// 信息正确
		msgJson = new NomalPojo();
		msgJson.setContent(obj);
		msgJson.setMsg("登录成功。");
		log4j.info("执行到这里: 登录成功。");
		session.removeAttribute("code");
		session.setAttribute("account", account);
		this.renderJson(msgJson);
	}

	/**
	 * 判断用户是否已登录
	 */
	public void isLogined() {
		boolean flag = this.getSession().getAttribute("account") != null ? true : false;
		BaseJsonPojo msgJson = new NomalPojo();

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("isLogined", flag);
		result.put("msg", "未登录。");
		msgJson.setContent(result);

		this.renderJson(msgJson);
	}

	/**
	 * 编辑器文件上传
	 */
	public void editorUpload() {
		HttpServletRequest request = this.getRequest();
		String uuid = UUID.randomUUID().toString();
		// 文件上传控制，保存到文件夹“editorfile”里，最大上传不超过50M(安全界限),采用“utf-8”编码
		UploadFile uploadFileTmp = this.getFile("files", "editorfile/" + uuid + "/", 50 * 1024 * 1024, "utf-8");
		log4j.info("执行到这里: " + Constant_PlanB_.LocalHost(request) + Constant_PlanB_.EditorfileResource + uuid
				+ File.separator + uploadFileTmp.getFileName());
		// 文件校验
		String msg = JfinalFileUtil.validatorFile(uploadFileTmp);
		if (msg == null) {
			this.renderText(Constant_PlanB_.LocalHost(request) + Constant_PlanB_.EditorfileResource + uuid
					+ File.separator + uploadFileTmp.getFileName());
		} else {
			this.renderText(msg);
		}
	}

	/**
	 * logo上传
	 */
	public void logoUpload() {
		// 清除上一次上传的图片
		UploadFile temp = null;
		if (null != (temp = (UploadFile) this.getSession().getAttribute("companyLogoFile"))) {
			temp.getFile().delete();
			this.getSession().removeAttribute("this.getSession()");
		}
		HttpServletRequest request = this.getRequest();
		// 文件上传控制，保存到文件夹“company”里，最大上传不超过50M(安全界限),采用“utf-8”编码
		UploadFile uploadFileTmp = this.getFile("files", "company", 50 * 1024 * 1024, "utf-8");
		log4j.info("执行到这里:  上传logo");
		// 文件校验
		String msg = JfinalFileUtil.validatorFile(uploadFileTmp);
		if (msg == null) {
			// 信息正确
			BaseJsonPojo msgJson = new NomalPojo();
			this.getSession().setAttribute("companyLogoFile", uploadFileTmp);
			msgJson.setMsg(
					Constant_PlanB_.LocalHost(request) + Constant_PlanB_.CompanyResource + uploadFileTmp.getFileName());
			this.renderJson(msgJson);
			return;
		} else {
			BaseJsonPojo msgJson = new ErrorPojo();
			msgJson.setMsg(msg);
			log4j.info("执行到这里: " + msg);
			this.renderJson(msgJson);
			return;
		}
	}

	/**
	 * 品种图片上传
	 */
	public void productImgUpload() {
		// 文件上传控制，保存到文件夹“company”里，最大上传不超过50M(安全界限),采用“utf-8”编码
		UploadFile uploadFileTmp = this.getFile("files", "product", 50 * 1024 * 1024, "utf-8");
		log4j.info("执行到这里:  上传product图");
		// 文件校验
		String msg = JfinalFileUtil.validatorFile(uploadFileTmp);
		if (msg == null) {
			// 信息正确
			BaseJsonPojo msgJson = new NomalPojo();
			msgJson.setMsg(Constant_PlanB_.ProductResource + uploadFileTmp.getFileName());
			this.renderJson(msgJson);
			return;
		} else {
			BaseJsonPojo msgJson = new ErrorPojo();
			msgJson.setMsg(msg);
			log4j.info("执行到这里: " + msg);
			this.renderJson(msgJson);
			return;
		}
	}

	// =============================== 管理员模块
	// ========================================
	public void adminProFile() {
		String account = (String) this.getSession().getAttribute("account");
		Record obj = Db.findFirst(" select * from tb_admin where account = ? ", account);
		Map<String, Object> result = new HashMap<String, Object>(0);
		result.put("account", obj.get("account"));
		result.put("email", obj.get("email"));
		result.put("telephone", obj.get("telephone"));
		result.put("userName", obj.get("userName"));
		result.put("headimg", obj.get("headimg"));
		this.renderJson(new NomalPojo(result));
	}

	// ============================== 修改管理员信息
	// =====================================
	public void modifyProFile() {
		String account = this.getPara("account");
		String email = this.getPara("email");
		String telephone = this.getPara("telephone");
		String userName = this.getPara("userName");
		String headimg = this.getPara("headimg");
		int effectLine = Db.update(
				" update tb_admin set email = ?, telephone = ? , userName = ? , headimg = ? where account = ? ", email,
				telephone, userName, headimg, account);
		if (effectLine > 0) {
			this.renderJson(new NomalPojo());
		} else {
			this.renderJson(new ErrorPojo("修改失败"));
		}
	}
}
